package com.zhiwei.gateway.service.impl;

import com.zhiwei.common.service.CacheService;
import com.zhiwei.gateway.dao.entity.AuthorityInfo;
import com.zhiwei.gateway.dao.entity.UserInfo;
import com.zhiwei.gateway.service.AuthorityInfoService;
import com.zhiwei.gateway.service.UserInfoService;
import com.zhiwei.gateway.service.UserTokenService;
import com.zhiwei.gateway.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * function
 * author zhiwei.yang
 * time 2020-2-27-16:27
 */
@Service
public class UserTokenServiceImpl implements UserTokenService {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private AuthorityInfoService authorityInfoService;
    @Autowired
    private CacheService cacheService;
    @Value("spring.application.name")
    private String appName;

    @Override
    public UserInfo getUserInfoByToken(String token) {

        //Token校验
        if(!this.checkToken(token)){
            return null;
        }
        Map<String, Object> claimMap = JwtUtil.parseJwtToken(token);
        if(CollectionUtils.isEmpty(claimMap)){
            return null;
        }
        String username = (String)claimMap.get(JwtUtil.NAME);
        return userInfoService.getUserInfoByName(username);
    }

    @Override
    public List<AuthorityInfo> queryAuthorityByToken(String token) {
        UserInfo userInfo = this.getUserInfoByToken(token);
        if(null == userInfo){
            return Collections.emptyList();
        }
        return authorityInfoService.queryAuthorityByUserId(userInfo.getUuid());
    }

    @Override
    public String createToken(String username) {
        String jwtToken = JwtUtil.createJwtToken(username);
        this.saveToken(username, jwtToken);
        return jwtToken;
    }

    @Override
    public void removeToken(String token) {
        cacheService.removeCacheObject(appName, token);
    }

    @Override
    public void saveToken(String username, String token) {
        cacheService.putCacheObject(appName, token, username);
    }

    @Override
    public boolean checkToken(String token) {
        return cacheService.isExistCacheKey(appName, token);
    }
}
